package com.simplehire.repository;

import com.simplehire.model.UserPermission;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Repository
public interface UserPermissionRepository extends JpaRepository<UserPermission, Long> {
    List<UserPermission> findByUserId(Long userId);

    List<UserPermission> findByUserIdAndExpiresAtAfter(Long userId, LocalDateTime now);

    Optional<UserPermission> findByUserIdAndPermission(Long userId, String permission);

    @Modifying
    @Query("DELETE FROM UserPermission up WHERE up.user.id = :userId AND up.permission = :permission")
    void deleteByUserIdAndPermission(@Param("userId") Long userId, @Param("permission") String permission);

    @Modifying
    @Query("DELETE FROM UserPermission up WHERE up.expiresAt < :now")
    void deleteExpiredPermissions(@Param("now") LocalDateTime now);
}